<script setup>
import 'leaflet/dist/leaflet.css'
import '@supermap/iclient-leaflet/css/index'

import iServerConfigUrl from '/iServerConfig.json?url'

import { Search, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import $ from 'jquery'
import axios from 'axios'

import L from 'leaflet'
import '@supermap/iclient-leaflet'
import 'proj4leaflet'

import { inject } from 'vue'

const optionsProps = {
    value: 'value',
    label: 'label'
}
</script>

<template>
    <el-card class="FGBSearchCard">
        <template #header>
            <div class="FGBSearchCardHeader">
                <span>地物查询</span>
            </div>
        </template>
        <span class="datasetListTitle">数据集列表</span>
        <el-select-v2 class="datasetsSelect" v-model="datasetName" filterable :props="optionsProps" :options="datasetsOptions"
            placeholder="请选择需要查询的数据集"></el-select-v2>
        <span class="datasetSqlTitle">SQL 查询 - 要素过滤器</span>
        <el-input class="sqlInput" v-model="sqlContent" :rows="6" type="textarea" placeholder="请输入要素过滤条件" resize="none"></el-input>
        <span class="maxFeaturesCountTitle">最多可返回的要素数量</span>
        <el-input-number class="maxFeaturesCount" v-model="maxFeaturesCount" :min="1"></el-input-number>
        <el-button class="button" :icon="Search" round @click="handleSearchedBtnClicked">查询</el-button>
        <el-button class="button" :icon="Delete" round @click="handleClearBtnClicked">清除</el-button>
    </el-card>
</template>

<script>
export default {
    name: 'FGBSearchLocation',
    data() {
        return {
            restMapUrl: undefined,
            restLayer: {},
            restDataUrl: undefined,
            datasourceName: 'dy',
            datasetName: '',
            datasetsOptions: [],
            sqlContent: 'SmID < 10',
            maxFeaturesCount: 1000,
            fgbLayer: undefined
        }
    },
    mounted() {
        var map = inject('map');

        axios.get(iServerConfigUrl).then(res => {
            var iServerConfig = res.data;
            this.restMapUrl = `${iServerConfig.urls.FGBSearchLocation.protocol}://${iServerConfig.urls.FGBSearchLocation.hostname}:${iServerConfig.urls.FGBSearchLocation.port}/${iServerConfig.urls.FGBSearchLocation.restMapUrl}`;
            this.restDataUrl = `${iServerConfig.urls.FGBSearchLocation.protocol}://${iServerConfig.urls.FGBSearchLocation.hostname}:${iServerConfig.urls.FGBSearchLocation.port}/${iServerConfig.urls.FGBSearchLocation.restDataUrl}`;

            // 还原 map 显示范围
            if (map._size.x !== document.body.clientWidth) {
                $("#map")[0].style.width = '';
                map._size.x = document.body.clientWidth;
            }

            // 定义 4490 坐标系
            const CRS_4490 = new L.Proj.CRS("EPSG:4490", "+proj=longlat +ellps=GRS80 +no_defs", {
                resolutions: [
                    0.04373046874998992,
                    0.02186523437499496,
                    0.01093261718749748,
                    0.00546630859374874,
                    0.00273315429687437,
                    0.001366577148437185,
                    0.0006832885742185925,
                    0.00034164428710929624,
                    0.00017082214355464812,
                    0.00008541107177732406,
                    0.00004270553588866203,
                    0.000021352767944331015,
                    0.000010676383972165508,
                    0.000005338191986082754,
                    0.000002669095993041377,
                    0.0000013345479965206884,
                    0.0000006672739982603442
                ],
                origin: [97.347425, 34.31465000089267]
            });
            map.options.crs = CRS_4490;
            map.flyTo([31.12, 104.48], 4);

            // 添加底图
            this.restLayer = new L.supermap.TiledMapLayer(this.restMapUrl);
            map.addLayer(this.restLayer);

            // 加载可查询的数据集选项
            this.loadDatasetsOptions();
        }).catch(err => {
            ElMessage.error(err.stack)
        });
    },
    methods: {
        // 加载可查询的数据集选项
        loadDatasetsOptions() {
            axios.get(`${this.restDataUrl}/datasources/${this.datasourceName}/datasets.json`).then(res => {
                this.datasetsOptions = res.data.datasetNames.map(datasetName => {
                    return {
                        label: datasetName,
                        value: datasetName
                    }
                });
            }).catch(err => {
                console.log(err);
            });
        },

        // 查询定位
        handleSearchedBtnClicked() {
            var map = this.restLayer._map;
            this.clearFGBLayers(map);
            if (this.datasetName.length === 0 || this.sqlContent.length === 0) {
                return;
            }

            var sqlParam = new L.supermap.GetFeaturesBySQLParameters({
                queryParameter: {
                    name: `${this.datasetName}@${this.datasourceName}`,
                    attributeFilter: this.sqlContent
                },
                maxFeatures: this.maxFeaturesCount,
                datasetNames: [`${this.datasourceName}:${this.datasetName}`]
            });

            var that = this;

            // 绑定图层添加后触发事件
            var fgbDataBounds = undefined;
            map.on('layeradd', layer => {
                if (layer.layer === that.fgbLayer) {
                    fgbDataBounds = undefined;
                } else if (layer.layer.feature !== undefined) {
                    var props = '';
                    var properties = layer.layer.feature.properties;
                    if (properties !== undefined) {
                        for (let key in properties) {
                            var value = properties[key];
                            if (value.length > 0) {
                                props += `${key}: ${properties[key]}<br />`;
                            }
                        }
                        if (props.length === 0) {
                            props = '属性为空';
                        }
                        layer.layer.bindPopup(props, {
                            autoClose: false,
                            closeButton: false
                        });
                    }

                    var tempBounds = layer.layer._bounds;
                    if (tempBounds === undefined) {
                        var latlng = layer.layer._latlng;
                        tempBounds = new L.latLngBounds([[latlng.lat * 0.99999, latlng.lng * 1.00001], [latlng.lat * 1.00001, latlng.lng * 0.99999]]);
                    }
                    if (fgbDataBounds === undefined) {
                        fgbDataBounds = tempBounds;
                    } else {
                        fgbDataBounds = fgbDataBounds.extend(tempBounds);
                    }
                    map.flyToBounds(fgbDataBounds, { maxZoom: map.options.maxZoom });
                }
            });

            // 添加 FGBLayer
            new L.supermap.FeatureService(this.restDataUrl).getFeaturesBySQL(sqlParam, function (serviceResult) {
                that.fgbLayer = new L.supermap.FGBLayer(serviceResult.result.newResourceLocation, {
                    strategy: 'all'
                });
                map.addLayer(that.fgbLayer);
            }, 'FGB');
        },

        // 清除按钮点击
        handleClearBtnClicked() {
            this.clearFGBLayers(this.restLayer._map);
        },

        // 清除 FGB 图层
        clearFGBLayers(map) {
            if (this.fgbLayer !== undefined && map.hasLayer(this.fgbLayer)) {
                map.eachLayer(layer => {
                    if (layer !== this.restLayer) {
                        layer.remove();
                    }
                });

                this.fgbLayer = undefined;
            }
        }
    }
}
</script>

<style scoped>
#map {
    width: 100%;
    height: calc(100vh - 81px);
    float: left;
}

#mapBaseInfo {
    float: left;
    position: absolute;
    z-index: 999;
    line-height: 20px;
    bottom: 0px;
    right: 0px;
}

#mouseLatlng {
    font-family: "Avenir", Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    text-align: left;
    color: #ffffff;
    margin: 0;
    font-size: 13px;
}

.FGBSearchCard {
    position: absolute;
    width: 360px;
    height: 570px;
    z-index: 999;
    background-color: rgba(240, 255, 255, 0.7);
    right: 0px;
    margin: 20px;
    border-radius: 20px;
}

.FGBSearchCardHeader {
    line-height: 32px;
    font-weight: 600;
    font-size: 24px;
}

.datasetListTitle {
    font-weight: 600;
    font-size: 18px;
    position: absolute;
    left: 26px;
    line-height: 32px;
}

.datasetsSelect {
    top: 110px;
    position: absolute;
    left: 0px;
    margin: 20px;
    width: calc(100% - 40px);
}

.datasetSqlTitle {
    font-weight: 600;
    font-size: 18px;
    position: absolute;
    left: 26px;
    line-height: 32px;
    top: 190px;
}

.sqlInput {
    top: 210px;
    position: absolute;
    left: 0px;
    margin: 20px;
    width: calc(100% - 40px);
}

.maxFeaturesCountTitle {
    font-weight: 600;
    font-size: 18px;
    position: absolute;
    left: 26px;
    line-height: 32px;
    top: 400px;
}

.maxFeaturesCount {
    top: 424px;
    position: absolute;
    left: 0px;
    margin: 20px;
    width: calc(100% - 40px);
}

.button {
    font-size: 16px;
    font-weight: 600;
}
</style>